package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter("/*")//servlet技术
@Slf4j
public class LoginCheckFilter implements Filter {

    public static final AntPathMatcher antPathMatcher=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //判断用户是否登陆过了，放行

        //判断依据
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String requestURI = httpServletRequest.getRequestURI();

        log.info("拦截到请求：{}",requestURI);

        String[] patterns = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        for (String pattern : patterns) {
            boolean match = antPathMatcher.match(pattern, requestURI);
            if(match){
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
        }

        //4-2、判断登录状态，如果已登录，则直接放行
        if(httpServletRequest.getSession().getAttribute("user") != null){
            log.info("用户已登录，用户id为：{}",httpServletRequest.getSession().getAttribute("user"));

            User user = (User) httpServletRequest.getSession().getAttribute("user");
                BaseContext.setCurrentId(user.getId());
                filterChain.doFilter(servletRequest,servletResponse);
                return;
        }

        Employee loginUser = (Employee) httpServletRequest.
                getSession().getAttribute("loginUser");
        if(loginUser!=null){
            BaseContext.setCurrentId(loginUser.getId());
            filterChain.doFilter(servletRequest, servletResponse);
            BaseContext.remove();
            return;
        }

        //没有登陆，拦截
        R r = R.error("NOTLOGIN");
        String jsonString = JSON.toJSONString(r);
        servletResponse.getWriter().write(jsonString);
    }
}
